package cn.hg.solon.youcan.system.provider;

import java.util.List;
import java.util.Map;

import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.api4j.select.Queryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.constant.WebConstants;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.system.entity.EqPosition;
import cn.hg.solon.youcan.system.entity.Position;
import cn.hg.solon.youcan.system.service.PositionService;

/**
 * @author 胡高
 */
@Component
public class EqPositionProvider implements PositionService {

    @Db("db1")
    private EasyQuery easyQuery;

    private Queryable<EqPosition> buildQuery(Map<String, Object> paraMap) {
        String word = (String)paraMap.get("word");
        String status = (String)paraMap.get("status");
        String sortField = (String)paraMap.get("sortField");
        String sortType = (String)paraMap.get("sortType");

        boolean customOrder = StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType);

        // FROM sys_notice AS t
        return this.easyQuery.queryable(EqPosition.class)
            // WHERE t.`status` = ${status} AND (t.`name` LIKE '%${word}%' OR t.`code` LIKE '%${word}%'')
            .where(w -> w.eq(StrValidator.isNotBlank(status), EqPosition::getStatus, status)
                .and(StrValidator.isNotBlank(word),
                    a -> a.like(EqPosition::getName, word)
                    .or().like(EqPosition::getCode, word)))
            // ORDER BY ${sortField} DESC
            .orderBy(customOrder, ob -> ob.sqlNativeSegment(CharSequenceUtil.toUnderlineCase(sortField)),
                !CharSequenceUtil.equalsIgnoreCase(sortType, WebConstants.ORDER_DIRECTION_DESC));
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.PositionService#checkUnique(cn.hg.solon.youcan.system.entity.Position)
     */
    @Override
    public boolean checkUnique(Position bean) {
        return !this.easyQuery
            // FROM sys_position AS t
            .queryable(EqPosition.class)
            // WHERE t.`code` = ${bean.code}
            .where(w -> w.eq(EqPosition::getCode, bean.getCode())
                // t.`id` <> ${bean.id}
                .ne(ObjUtil.isNotNull(bean.getId()), EqPosition::getId, bean.getId()))
            .any();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.PositionService#delete(java.util.List)
     */
    @Tran
    @Override
    public boolean delete(List<Integer> idList) {
        return this.easyQuery.deletable(EqPosition.class)
            .where(w -> w.in(EqPosition::getId, idList))
            .executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.PositionService#get(java.lang.Integer)
     */
    @Override
    public Position get(Integer id) {
        return this.easyQuery.queryable(EqPosition.class).whereById(id).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.PositionService#insert(cn.hg.solon.youcan.system.entity.Position)
     */
    @Tran
    @Override
    public boolean insert(Position bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "岗位编码已经存在，请更换其它值！");
        }

        EqPosition cloneBean = BeanUtil.copyProperties(bean, EqPosition.class);

        return this.easyQuery.insertable(cloneBean).executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.PositionService#pageBy(int, int, java.util.Map)
     */
    @Override
    public PageResult<? extends Position> pageBy(int pageNumber, int pageSize, Map<String, Object> paraMap) {
        EasyPageResult<EqPosition> pageList = this.buildQuery(paraMap).toPageResult(Convert.toLong(pageNumber), pageSize);

        PageResult<EqPosition> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(Convert.toInt(pageList.getTotal()));

        return result;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.PositionService#update(cn.hg.solon.youcan.system.entity.Position)
     */
    @Tran
    @Override
    public boolean update(Position bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "岗位编码已经存在，请更换其它值！");
        }

        EqPosition cloneBean = (EqPosition)this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyQuery.updatable(cloneBean).executeRows() > 0;
    }

}
